<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'unitmanage:unitBuilding:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
    destroyOnClose={true}
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <template #footer>
      <Button   @click="closeDrawer">  <Icon icon="i-ant-design:close-outlined" />取消</Button>
      <Button  v-if="record.isNewRecord!=false"  @click="handleRegionEdit">  <Icon icon="i-ant-design:bank-outlined" />下一步</Button>
      <Button v-if="record.isNewRecord!=false"  @click="addBuild">新增建筑</Button>
      <Button type="primary" @click="handleSubmit"> <Icon icon="i-ant-design:check-outlined" />确认</Button>
    </template>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
  <template>
    <ViewsUnitmanageUnitRegionForm @register="registerRegionDrawer" />
  </template>
</template>
<script lang="ts" setup name="ViewsUnitmanageUnitBuildingForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { UnitBuilding, unitBuildingSave, unitBuildingForm, unitBuildingListData } from '/@/api/unitmanage/unitBuilding';
  import { Office, officeTreeData, officeListData, officeTreeDataList } from '/@/api/sys/office';
  import { useDrawer } from '/@/components/Drawer';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { Modal, Button } from 'ant-design-vue';
  import ViewsUnitmanageUnitRegionForm from '/@/views/unitmanage/unitRegion/form.vue';


  const emit = defineEmits(['success', 'register']);
  
  const { t } = useI18n('unitmanage.unitBuilding');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<UnitBuilding>({} as UnitBuilding);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.tid ? t('新增') : t('编辑'),
  }));

  const buildingName = ref('');
  const showContractDialog = ref(false);
  const EnterpriseParams = ref<Recordable>({
    name: ''
  });

  // 使用 computed 动态计算 params 对象
  const selectParams = computed(() => {
    return {
      name: buildingName.value,
    };
  });

  const UnitAbutSituationName = ref('');

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('所属主体'),
      field: 'unitCode',
      fieldLabel: 'enterpriseName',
      component: 'TreeSelect',
      componentProps: () => {
        return {
          placeholder: t('请输入主体名称'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          allowClear: true,
          filterTreeNode: false,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
        };
      },
    },
    {
      label: t('建筑名称'),
      field: 'name',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('详细地址'),
      field: 'location',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('占地面积'),
      field: 'occupyArea',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
      componentProps: {},
    },
    {
      label: t('建筑类型'),
      field: 'buildingType',
      component: 'Select',
      componentProps: {
        maxlength: 100,
        options: [
          { label: '民用建筑', value: '11001' },
          { label: '工业建筑', value: '11002' },
          { label: '仓库建筑', value: '11003' },
          { label: '储罐建筑', value: '11004' },
          { label: '堆场', value: '11005' },
          { label: '装置', value: '11006' },
        ],
      },
    },
    {
      label: t('周边建筑'),
      field: 'unitAbutSituation',
      fieldLabel: 'remarks',
      component: 'TreeSelect',
      componentProps: {
        api: unitBuildingListData,
        params: selectParams,
        resultField: 'list',
        fieldNames: { label: 'name', value: 'id' },
        allowClear: true,
        immediate: false,
        each: false,
        showSelect: true,
        optionFilterProp: 'label',
        showSearch: true,
        treeCheckable: true,
        onSearch: (value) => {
          buildingName.value = value;
          // console.log('输入的值:', value);   
        },
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await unitBuildingForm(data);
    record.value = (res.unitBuilding || {}) as UnitBuilding;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });
  let isSubmitSuccess = false; // 新增标志位，用于记录提交是否成功
  async function handleSubmit() {
    try {
      let data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        tid: record.value.tid,
        isNewRecord: record.value.isNewRecord,
      };
      const unitAbutSituation = data.unitAbutSituation;
      console.log('unitAbutSituation', unitAbutSituation);
      const res = await unitBuildingSave(params, data);
      showMessage(res.message);
      if (res.result === 'true') { // 检查接口返回的 result 值
          isSubmitSuccess = true;
          if (record.value.isNewRecord) {
              showContractDialog.value = true;
          }
      } else {
          isSubmitSuccess = false;
      }
      // setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }

  

  // // 定义 handleRegionEdit 方法
  // const handleRegionEdit = () => {
  //   router.push({
  //     path: `/unitmanage/unitRegion/list`,
  //     query: {
  //       unitCode: record.value.unitCode // 传递 unitCode 参数
  //     }
  //   });
  // };

  // 新增 addBuild 方法
  const addBuild = async () => {
    console.log('新增建筑');
    await handleSubmit();
    await resetFields();
  };

  //打开区域表单
  const [registerRegionDrawer, { openDrawer: openRegionDrawer }] = useDrawer();
  const handleRegionEdit=async ()=>{
    Modal.confirm({
      title: t('是否确认进入区域编辑'),
      onOk: async () => {
        await handleSubmit();
        if (isSubmitSuccess) { // 检查提交是否成功
        await openRegionDrawer();
        await resetFields();
    } else {
        showMessage('缺少必填数据，请检查后提交');
    }  
      },
      onCancel: () => {
        // 点击取消时不需要额外操作，提示框会自动关闭
      },
    });
  }
</script>